{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import statsmodels.api as sm\n",
    "from statsmodels.formula.api import ols\n",
    "\n",
    "# 读取数据\n",
    "df = pd.read_excel('整合后的文件.xlsx')\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "# 设置全局字体，避免中文乱码\n",
    "plt.rcParams['figure.dpi'] = 300  # 提高所有图形的分辨率\n",
    "config = {\n",
    "    \"font.family\": 'serif',\n",
    "    \"font.size\": 16,\n",
    "    \"mathtext.fontset\": 'stix',\n",
    "    \"font.serif\": ['SimSun'],  # 使用宋体，前提是系统安装了该字体\n",
    "}\n",
    "plt.rcParams.update(config)  # 更新配置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import seaborn as sns\n",
    "#  将分类变量转换为类别型\n",
    "df['励磁波形'] = df['励磁波形'].astype('category')\n",
    "df['磁芯材料'] = df['磁芯材料'].astype('category')\n",
    "\n",
    "# 进行双因素方差分析，包括所有两两交互作用\n",
    "model = ols('磁芯损耗 ~ C(温度) + C(励磁波形) + C(磁芯材料) + C(温度):C(励磁波形) + C(温度):C(磁芯材料) + C(励磁波形):C(磁芯材料)', data=df).fit()\n",
    "anova_table = sm.stats.anova_lm(model, typ=2)\n",
    "\n",
    "# 输出ANOVA结果\n",
    "print(anova_table)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 5.1 温度和励磁波形的交互作用\n",
    "plt.figure(figsize=(10, 6))  # 调整图像尺寸\n",
    "sns.pointplot(x='温度', y='磁芯损耗', hue='励磁波形', data=df, dodge=True, markers=['o', 's', 'D', '^'], \n",
    "              capsize=0.1, err_kws={'linewidth': 1}, palette='colorblind')  # 使用 Seaborn 的 pointplot 和自定义样式\n",
    "plt.title('温度与励磁波形的交互作用', fontsize=25, pad=20)\n",
    "plt.xlabel('温度 (°C)', fontsize=25, labelpad=10)\n",
    "plt.ylabel('磁芯损耗 (W/m^3)', fontsize=25, labelpad=10)\n",
    "plt.legend(title='励磁波形', fontsize=15)\n",
    "plt.grid(True)\n",
    "plt.show()\n",
    "\n",
    "# 5.2 温度和磁芯材料的交互作用\n",
    "plt.figure(figsize=(10, 6))\n",
    "sns.pointplot(x='温度', y='磁芯损耗', hue='磁芯材料', data=df, dodge=True, markers=['o', 's', 'D', '^'], \n",
    "              capsize=0.1, err_kws={'linewidth': 1}, palette='colorblind')  # 使用 colorblind 调色板\n",
    "plt.title('温度与磁芯材料的交互作用', fontsize=25, pad=20)\n",
    "plt.xlabel('温度 (°C)', fontsize=25, labelpad=10)\n",
    "plt.ylabel('磁芯损耗 (W/m^3)', fontsize=25, labelpad=10)\n",
    "plt.legend(title='磁芯材料', fontsize=15)\n",
    "plt.grid(True)\n",
    "plt.show()\n",
    "\n",
    "# 5.3 励磁波形和磁芯材料的交互作用\n",
    "plt.figure(figsize=(10, 6))\n",
    "sns.pointplot(x='励磁波形', y='磁芯损耗', hue='磁芯材料', data=df, dodge=True, markers=['o', 's', 'D', '^'], \n",
    "              capsize=0.1, err_kws={'linewidth': 1}, palette='colorblind')  # 使用 colorblind 调色板和自定义样式\n",
    "plt.title('励磁波形与磁芯材料的交互作用', fontsize=25, pad=20)\n",
    "plt.xlabel('励磁波形', fontsize=25, labelpad=10)\n",
    "plt.ylabel('磁芯损耗 (W/m^3)', fontsize=25, labelpad=10)\n",
    "plt.legend(title='磁芯材料', fontsize=15)\n",
    "plt.grid(True)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "# 创建3个并排的子图\n",
    "fig, axes = plt.subplots(1, 3, figsize=(18, 4))  # 1行3列，调整图像尺寸\n",
    "\n",
    "# 5.1 温度和励磁波形的交互作用\n",
    "sns.pointplot(ax=axes[0], x='温度', y='磁芯损耗', hue='励磁波形', data=df, dodge=True, \n",
    "              markers=['o', 's', 'D', '^'], capsize=0.1, err_kws={'linewidth': 1}, palette='colorblind')\n",
    "axes[0].set_title('温度与励磁波形的交互作用', fontsize=19, pad=20)  # 增大标题字体\n",
    "axes[0].set_xlabel('温度 (°C)', fontsize=15, labelpad=12)  # 增大x轴标签字体\n",
    "axes[0].set_ylabel('磁芯损耗 (W/m^3)', fontsize=15, labelpad=12)  # 增大y轴标签字体\n",
    "axes[0].legend(title='励磁波形', fontsize=13, title_fontsize=13, loc='upper right')  # 增大图例字体并移动到右上角\n",
    "axes[0].grid(True)\n",
    "\n",
    "# 5.2 温度和磁芯材料的交互作用\n",
    "sns.pointplot(ax=axes[1], x='温度', y='磁芯损耗', hue='磁芯材料', data=df, dodge=True, \n",
    "              markers=['o', 's', 'D', '^'], capsize=0.1, err_kws={'linewidth': 1}, palette='colorblind')\n",
    "axes[1].set_title('温度与磁芯材料的交互作用', fontsize=19, pad=20)  # 增大标题字体\n",
    "axes[1].set_xlabel('温度 (°C)', fontsize=15, labelpad=12)  # 增大x轴标签字体\n",
    "axes[1].set_ylabel('磁芯损耗 (W/m^3)', fontsize=15, labelpad=12)  # 增大y轴标签字体\n",
    "axes[1].legend(title='磁芯材料', fontsize=13, title_fontsize=13, loc='upper right')  # 增大图例字体并移动到右上角\n",
    "axes[1].grid(True)\n",
    "\n",
    "# 5.3 励磁波形和磁芯材料的交互作用\n",
    "sns.pointplot(ax=axes[2], x='励磁波形', y='磁芯损耗', hue='磁芯材料', data=df, dodge=True, \n",
    "              markers=['o', 's', 'D', '^'], capsize=0.1, err_kws={'linewidth': 1}, palette='colorblind')\n",
    "axes[2].set_title('励磁波形与磁芯材料的交互作用', fontsize=19, pad=20)  # 增大标题字体\n",
    "axes[2].set_xlabel('励磁波形', fontsize=15, labelpad=12)  # 增大x轴标签字体\n",
    "axes[2].set_ylabel('磁芯损耗 (W/m^3)', fontsize=15, labelpad=12)  # 增大y轴标签字体\n",
    "axes[2].legend(title='磁芯材料', fontsize=13, title_fontsize=13, loc='upper right')  # 增大图例字体并移动到右上角\n",
    "axes[2].grid(True)\n",
    "\n",
    "# 调整布局以避免标题和标签重叠\n",
    "plt.tight_layout()\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = pd.read_excel('整合后的文件.xlsx')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 提取材料、温度、频率、磁芯损耗、励磁波形\n",
    "material = data['磁芯材料']            # 材料：材料1、材料2、材料3、材料4\n",
    "temperature = data['温度']          # 温度：25、50、70、90摄氏度\n",
    "frequency = data['频率']            # 频率：50000—500000 Hz\n",
    "core_loss = data['磁芯损耗']       # 磁芯损耗：w/m^3\n",
    "waveform = data['励磁波形']        # 励磁波形：正弦波、三角波、梯形波\n",
    "\n",
    "# 将材料和励磁波形转为分类变量\n",
    "material = material.astype('category')\n",
    "waveform = waveform.astype('category')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 单因素分析\n",
    "## 4.1 温度对磁芯损耗的影响\n",
    "plt.figure(figsize=(8, 6))\n",
    "bins = [0, 25, 50, 75, 100]  # 自定义温度区间\n",
    "categories = pd.cut(temperature, bins)\n",
    "sns.boxplot(x=categories, y=core_loss)\n",
    "plt.xlabel('温度区间')\n",
    "plt.ylabel('磁芯损耗 (W/m^3)')\n",
    "plt.title('不同温度对磁芯损耗的影响')\n",
    "plt.grid(True)\n",
    "plt.show()\n",
    "\n",
    "## 4.2 励磁波形对磁芯损耗的影响 (单因素方差分析)\n",
    "anova_waveform = stats.f_oneway(*[core_loss[waveform == w] for w in waveform.unique()])\n",
    "print('ANOVA for Waveform:', anova_waveform)\n",
    "\n",
    "## 4.3 磁芯材料对磁芯损耗的影响 (单因素方差分析)\n",
    "anova_material = stats.f_oneway(*[core_loss[material == m] for m in material.unique()])\n",
    "print('ANOVA for Material:', anova_material)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# 5. 双因素协同作用分析\n",
    "# 5.1 温度和励磁波形的交互作用\n",
    "plt.figure(figsize=(8, 6))\n",
    "interaction_plot(temperature, waveform, core_loss, colors=['red', 'blue', 'green'])\n",
    "plt.xlabel('温度 (°C)')\n",
    "plt.ylabel('磁芯损耗 (W/m^3)')\n",
    "plt.title('温度与励磁波形的交互作用')\n",
    "plt.grid(True)\n",
    "plt.show()\n",
    "\n",
    "# 5.2 温度和磁芯材料的交互作用\n",
    "plt.figure(figsize=(8, 6))\n",
    "interaction_plot(temperature, material, core_loss, colors=['red', 'blue', 'green', 'purple'])\n",
    "plt.xlabel('温度 (°C)')\n",
    "plt.ylabel('磁芯损耗 (W/m^3)')\n",
    "plt.title('温度与磁芯材料的交互作用')\n",
    "plt.grid(True)\n",
    "plt.show()\n",
    "\n",
    "# 确保将变量转换为字符串类型\n",
    "waveform = waveform.astype(str)\n",
    "material = material.astype(str)\n",
    "\n",
    "# 5.3 励磁波形和磁芯材料的交互作用\n",
    "plt.figure(figsize=(8, 6))\n",
    "interaction_plot(waveform, material, core_loss, colors=['red', 'blue', 'green', 'purple'])\n",
    "plt.xlabel('励磁波形')\n",
    "plt.ylabel('磁芯损耗 (W/m^3)')\n",
    "plt.title('励磁波形与磁芯材料的交互作用')\n",
    "plt.grid(True)\n",
    "plt.show()\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py38torch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
